package com.unieagle.exam.app;

import static android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS;

import java.io.File;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.unieagle.exam.http.IVolleyListener;
import com.unieagle.exam.http.TaskHelper;
import com.unieagle.exam.http.VolleyRequest;
import com.unieagle.exam.http.VolleyTask;
import com.unieagle.exam.model.CheckVersionResult;

public class Updater implements IVolleyListener{
    private final static String TAG = "Updater";
    private long mTaskDownloadId = 0;
    private DownloadManager downloadManager;
    private Context mContext;
    private String downloadPath;
    private String downloadUrl;
    private String versionName;
    private boolean hasCheck = false;
    private boolean hasJump = false;
    public Updater(Context context){
        mContext = context;
    }

    public void start(){
        if(!hasCheck) {
            checkVersion();
        }
    }

    private void checkVersion(){
        VolleyTask task = TaskHelper.createCheckVersionTask();
        task.setVolleyListener(this);
        VolleyRequest.getInstance().request(task);
    }

    //使用系统下载器下载
    private void downloadAPK(String versionUrl, String versionName) {

        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(false);
        //漫游网络是否可以下载 设置文件类型，可以在下载结束后自动打开该文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
        request.setMimeType(mimeString);
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);
        //sdcard的目录下的download文件夹，必须设置
        request.setDestinationInExternalPublicDir("/download/", versionName);
        //将下载请求加入下载队列
        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); //加入下载队列后会给该任务返回一个long型的id，
        // 通过该id可以取消任务，重启任务等等
        mTaskDownloadId = downloadManager.enqueue(request);
        //注册广播接收者，监听下载状态
        mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {checkDownloadStatus();//检查下载状态 } };
        }
    };
    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskDownloadId);
        //筛选下载任务，传入任务ID，可变参数
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status)
            {
                case DownloadManager.STATUS_PAUSED:
                    Log.i(TAG,">>>下载暂停");
                case DownloadManager.STATUS_PENDING:
                    Log.i(TAG,">>>下载延迟");
                case DownloadManager.STATUS_RUNNING:
                    Log.i(TAG,">>>正在下载");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    Log.i(TAG,">>>下载完成");
                    //下载完成安装APK //
                    downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + versionName;
                    installAPK(new File(downloadPath));
                    break;
                case DownloadManager.STATUS_FAILED:
                    Log.i(TAG,">>>下载失败");
                    break;
            }
        }
    }

    @Override
    public void onComplete(VolleyTask task, Object result) {
        hasCheck = true;
        downloadUrl = ((CheckVersionResult)result).getUpdate_url();
        versionName = ((CheckVersionResult)result).getLatest_version();
        if(!TextUtils.isEmpty(downloadUrl)){
            try{
                downloadAPK(downloadUrl, versionName);
            }catch(IllegalArgumentException e) {
                e.printStackTrace();
                if(!hasJump){
                    jumpDMSettingIntent();
                    Toast.makeText(mContext,"有新版本更新，请启用下载管理器！",Toast.LENGTH_SHORT).show();
                    hasJump = true;
                }
                hasCheck = false;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            Log.e(TAG,"NULL URL");
        }
    }

    private void jumpDMSettingIntent() {
        Intent localIntent = new Intent();
        String dmName = "com.android.providers.downloads";
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction(ACTION_APPLICATION_DETAILS_SETTINGS);
            localIntent.setData(Uri.fromParts("package", dmName, null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", dmName);
        }
        mContext.startActivity(localIntent);
    }

    @Override
    public void onError(VolleyTask task, VolleyError volleyError) {
    }

    protected void installAPK(File file)
    {
        if (!file.exists())
            return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + file.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

}
